package br.com.uniban.mdb;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;

import org.jboss.ejb3.annotation.RemoteBinding;

@Stateless
@RemoteBinding(jndiBinding=SendEmailRemote.JNDI)
public class SendEmailEJB implements SendEmailRemote {
	@Resource(mappedName="ConnectionFactory")
	private QueueConnectionFactory connectionFactory;
	@Resource(mappedName = "queue/sendEmailQueue")
	private Queue queue;

	@Override
	public void sendMail(String from,String to, String subject, String msg) {
		try {
			QueueConnection connection = connectionFactory.createQueueConnection();
			QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
			MessageProducer producer = session.createProducer(queue);
			
			MapMessage mapMessage = session.createMapMessage();
			mapMessage.setString(SendEmailRemote.FROM, from);
			mapMessage.setString(SendEmailRemote.TO, to);
			mapMessage.setString(SendEmailRemote.SUBJECT, subject);
			mapMessage.setString(SendEmailRemote.MSG, msg);
			
			producer.send(mapMessage);
			connection.start();
			connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
